package com.wechat.gateway.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 白名单配置
 */
@Data
@Component
@ConfigurationProperties(prefix = "gateway.whitelist")
public class WhitelistConfig {

    /**
     * 不需要token验证的路径
     */
    private List<String> authPaths = new ArrayList<>();

    /**
     * 不需要加密的路径
     */
    private List<String> encryptPaths = new ArrayList<>();

    /**
     * 检查路径是否在认证白名单中
     */
    public boolean isAuthWhitelist(String path) {
        if (path == null) {
            return false;
        }

        return authPaths.stream().anyMatch(whitePath -> {
            if (whitePath.endsWith("/**")) {
                // 通配符匹配
                String prefix = whitePath.substring(0, whitePath.length() - 3);
                return path.startsWith(prefix);
            } else if (whitePath.endsWith("/*")) {
                // 单级通配符
                String prefix = whitePath.substring(0, whitePath.length() - 2);
                return path.startsWith(prefix) && !path.substring(prefix.length()).contains("/");
            } else {
                // 精确匹配
                return path.equals(whitePath);
            }
        });
    }

    /**
     * 检查路径是否在加密白名单中
     */
    public boolean isEncryptWhitelist(String path) {
        if (path == null) {
            return false;
        }

        return encryptPaths.stream().anyMatch(whitePath -> {
            if (whitePath.endsWith("/**")) {
                String prefix = whitePath.substring(0, whitePath.length() - 3);
                return path.startsWith(prefix);
            } else if (whitePath.endsWith("/*")) {
                String prefix = whitePath.substring(0, whitePath.length() - 2);
                return path.startsWith(prefix) && !path.substring(prefix.length()).contains("/");
            } else {
                return path.equals(whitePath);
            }
        });
    }
} 